package com.ssd.demo.base.util.simplepdf;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import com.ssd.demo.base.util.simplepdf.pdfhandler.NewPageHandler;

public class SimplePdf {

    private static Map<String, CellInc> defaultPdfHandler;
    static {
        defaultPdfHandler = new HashMap<String, CellInc>();
        // 注册换页处理
        CellInc newPageCell = new CellInc(null, new NewPageHandler());
        newPageCell.setNewPage(true);
        defaultPdfHandler.put("newPage", newPageCell);

    }

    /**
     * 指令提取 //<!(.*?)!> <![^!>]*!>
     */
    private static final Pattern CELLINTPATTERN = Pattern.compile("<!([^<!>]*)!>");

    /**
     * 内容提取
     */
    private static final Pattern CELLCONTENTPATTERN = Pattern.compile("!>([^<!>]*)<!");

    /**
     * @param content 转化
     * @param root
     * @param os
     * @throws DocumentException
     * @throws IOException
     */
    public void convertPdf(String content, Map<String, Object> root, OutputStream os) throws DocumentException, IOException {
        List<String> incs = getIncs(content);// 合并和下一句
        List<CellInc> lisCells = preHandleCell(incs);
        List<String> incContents = getIncsContents(content);

        convert(lisCells, incContents, root, os);
    }

    /**
     * @param cellIncs 这里需要自定义加入 preHandleCell(List<String> cellIncs,
     *            Map<String, PdfHandler> cusHandler)
     * @return
     */
    private List<CellInc> preHandleCell(List<String> cellIncs) {

        List<CellInc> list = new ArrayList<CellInc>(cellIncs.size());
        for (String cellStr : cellIncs) {

            if (defaultPdfHandler.containsKey(cellStr)) {
                list.add(defaultPdfHandler.get(cellStr));
            } else {
                // 位置(default left) 字体（size style）
                CellInc cellInc = null;
                if ("".equals(cellStr)) {
                    cellInc = new CellInc(false, Paragraph.ALIGN_LEFT, 18, Font.NORMAL, null);
                } else {
                    cellStr = cellStr.replaceFirst("center", Paragraph.ALIGN_LEFT + "")// 处理居中
                            .replaceFirst("right", Paragraph.ALIGN_RIGHT + "")// 处理居右
                            .replaceFirst("big", "24 " + Font.BOLD)// 处理 大字体
                            .replaceFirst("middle", "18 " + Font.NORMAL)// 处理中字体
                            .replaceFirst("small", "12 " + Font.NORMAL)// 处理小字体
                            .replaceFirst("mLine", "12 " + Font.UNDERLINE);// 处理下滑线字体
                    String[] str = cellStr.split("\\s+");
                    if (str.length == 3) {
                        cellInc = new CellInc(false, Integer.parseInt(str[0]), Integer.parseInt(str[1]), Integer.parseInt(str[2]), null);
                    } else {
                        cellInc = new CellInc(false, Paragraph.ALIGN_LEFT, Integer.parseInt(str[0]), Integer.parseInt(str[1]), null);
                    }
                }
                list.add(cellInc);
            }
        }

        return null;
    }

    /**
     * //是否新页 位置 字体（size style）
     * 
     * @param incs
     * @param incContents
     * @param os
     * @throws DocumentException
     */
    private void convert(List<CellInc> cellIncs, List<String> incContents, Map<String, Object> root, OutputStream os) throws DocumentException {

        Document doc = new Document(PageSize.A4);
        PdfWriter.getInstance(doc, os);
        doc.open();
        int i = 0;
        Paragraph ph = new Paragraph();
        for (CellInc CellInc : cellIncs) {
            if (CellInc.excute(doc, root, incContents.get(i++), ph)) {
                ph = new Paragraph();
            }
        }

        doc.add(ph);
    }

    /**
     * 获取指令集合
     * 
     * @param content
     * @return
     */
    private List<String> getIncs(String content) {
        List<String> incs = new ArrayList<String>();

        Matcher matcher = CELLINTPATTERN.matcher(content);
        while (matcher.find()) {
            incs.add(matcher.group(1));
        }
        return incs;
    }

    /**
     * 获取指令 编译内容
     * 
     * @param content
     * @return
     */
    private List<String> getIncsContents(String content) {
        List<String> incContents = new ArrayList<String>();
        Matcher matcher = CELLCONTENTPATTERN.matcher(content);
        while (matcher.find()) {
            incContents.add(matcher.group(1));
        }
        return incContents;
    }

}
